import { deepClone } from '@/utils/deepClone' // 深拷贝
import router from './index'
// 处理路由展示列表树形格式 (如果所有路由数据是在同一级，需要调用这个方法)
export const formatRouterTree = (data) => {
    let parents = data.filter((i) => i.pid === 0),
        children = data.filter((item) => item.pid !== 0)

    dataToTree(parents, children)
    function dataToTree(parents, children) {
        parents.map((p) => {
            children.map((c, i) => {
                let _c = deepClone(children)
                _c.splice(i, 1)
                dataToTree([c], _c)
                if (p.children) {
                    p.children.push(c)
                } else {
                    p.children = [c]
                }
            })
        })
    }
}

// vite中获取文件
const modules = import.meta.glob([
    '../views/*.vue',
    '../views/*/*.vue',
    '../views/*/*/*.vue',
    '../views/*/*/*/*.vue',
    '../components/admin/layout.vue',
])

// 处理路由所需格式
export const generateRouter = (userRouters) => {
    // return userRouters
    let newRouter = null
    if (userRouters) {
        newRouter = userRouters.map((i) => {
            let routes = {
                path: i.path,
                name: i.name,
                meta: i.meta,
                component: i.component === '' ? modules[`../components/admin/layout.vue`] : modules[`../views${i.component}.vue`],
            }
            if (i.children) {
                routes.children = generateRouter(i.children)
            }
            return routes
        })
    }
    return newRouter
}

/**
 * 添加动态路由
 */
export function setAdminAddRoute(routes) {
    if (routes && routes.length > 0) {
        routes.forEach((route) => {
            const routeName = route.name
            if (!router.hasRoute(routeName)) {
                router.addRoute(route)
            }
        })
    }
}